package com.dongdongshop.controller;

import com.dk.data.R;
import com.dk.enums.ResultEnum;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.User;
import com.dongdongshop.service.TbSeckillGoodService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

//秒杀商品表
@Controller
@RequestMapping("seckillGood")
public class TbSeckillGoodController {


    @DubboReference(timeout = 10000000)//设置超时时间
    TbSeckillGoodService tgs;//


    @Autowired
    RedisTemplate redisTemplate;


    //跳转秒杀页面
    @RequestMapping("tiao")
    public String tiao(){
        return "seckill-index";
    }


    //查询全部放入缓存
    //跳转页面预热
    @RequestMapping("addall")
    public String addall(){
        tgs.addall();
        return "seckill-index";
    }


    //取出缓存中数据
    @RequestMapping("getall")
    @ResponseBody
    public R<List<TbSeckillGoods>> getall(){
        List <TbSeckillGoods> ls  =tgs.getall();
        return R.ok().setData(ls);
    }


    //跳转立即抢购详情页
    @RequestMapping("getorder")
    public String getorder(Long id, Model model){
        TbSeckillGoods goods = tgs.getorder(id);
        model.addAttribute("seckillGoods",goods);
        return "seckill-item";
    }



    //抢购生成订单
    @RequestMapping("createorder")
    @ResponseBody
    public R createorder(Long sekillid){
        //先判断用户是否登录，根据秒杀商品的id生成订单，然后跳转支付页面
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user==null){
            return R.response(ResultEnum.USER_LOGINERROR);//用户未登录
        }
        long result=tgs.createorder(sekillid,user.getUsername());
        if(result<0){
            return R.response(ResultEnum.SELL_OVER);//卖完了。没货了
        }
        String s = String.valueOf(result);//Long类型，js中会丢失精度
        return R.ok().setData(s);
    }


    //异步页面
    @RequestMapping("getorderidindex")
    public String getorderidindex(){
        return "getorderidindex";
    }


    //返回orderid
    @RequestMapping("getorderid")
    @ResponseBody
    public R getorderid() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return R.response(ResultEnum.USER_LOGINERROR);//用户未登录
        }
        String username = user.getUsername();
        Long orderid = (Long) redisTemplate.boundHashOps("seckill_orderid").get(username);
        if (orderid == null) {
            return R.error().setData("请到待支付页面支付");
        }
        return R.ok().setData(orderid.toString());
    }

}
